<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Profile_model extends CI_Model
{

	/**
	 * Constructor
	 *
	 * @access	public
	 */
	function __construct()
	{
		parent::__construct();
	}

	function get_user_info($userid)
	{
		$this->db->select('*');
		$this->db->from('user');
		$this->db->where('id', $userid);
		$query = $this->db->get();
		return $query->row();
	}
	
	function delete_avatar($userid)
	{
		$this->db->select('id, avatar');
		$this->db->where('id', $userid);
		$this->db->from('user');
		$query = $this->db->get();
		return $query->row_array();
	}
	
	function update_profile($userid)
	{
		//$this->load->helper('file');
		$avatar = $this->upload->data();
		$fields = array(
			'fullname' 	=> $this->input->post('fullname'),
			'address'	=> $this->input->post('address'),

		);
		
		$fields2 = array(
			'fullname' 	=> $this->input->post('fullname'),
			'address'	=> $this->input->post('address'),
			'avatar'	=> $avatar['file_name'],
		);
		
		if($this->input->post('newpassword'))
		{
			$this->update_password($this->input->post('newpassword'), $this->user->id);
		}
		
		if($avatar['file_name'] == '')
		{
			$this->db->where('id', $userid);
			$this->db->set($fields);
		}
		else
		{			
			$photo = $this->delete_avatar($userid); // get function delete avata with userid
			$file = $photo['avatar']; //set field avtar of userid
			@unlink('uploads/avatars/'.$file); //delete file on database and path, @ to disable error
			$this->db->where('id', $userid);
			$this->db->set($fields2);
		}
		
		$this->db->update('user');
		
		
	}
	
	function update_password($password, $id, $change = FALSE)
	{
		$hash = sha1(microtime());
		$salt = $this->config->item('auth');
		$salt = $salt['salt'];

		$password = sha1($salt.$hash.$password);

		$change = $change ? '1' : '0';
		$data = array(
				'change_password'		=> $change,
				'password'				=> $password,
				'hash' 					=> $hash
        );

		$this->db->where('id', $id);
		$this->db->update('user', $data);
		
		return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
	}
	
	public function check_pass()
	{
		//echo $this->user->password; exit();
		
		//echo $password; exit();
        if( $password == $this->user->password)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}

// END pages_model.php
/* Location: ./application/models/profile_model.php */